from django.contrib.auth import get_user_model
from rest_framework import serializers
from utils.now import my_now
from .models import *
from apps.sale.models import *
User = get_user_model()


class SaleVisitingSerializer(serializers.ModelSerializer):
    queryset = Customer.objects.all()
    F001 = serializers.SlugRelatedField(queryset=queryset,slug_field='B001',label='客户')

    def validate(self, data):
        data['B002'] = self.context['request'].user.username  # 修改字段的代码放在此处是因为重写create方法会导致外键自动查找失效
        contacts = [i.B001 for i in Contacts.objects.filter(F001__B001=data['F001'])]
        if data['B001'] not in contacts:
            raise serializers.ValidationError("您输入的客户或联系人姓名不存在！")
        return data

    class Meta:
        model = SaleVisiting
        fields = '__all__'

